package com.cmcc.aregister.cs.http;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;

import android.util.Log;

import com.cmcc.aregister.cs.util.MyLogger;
import com.cmcc.aregister.cs.util.Utils;

/**
 * @author swq
 */
public class HttpConnection {

    private static final MyLogger logger = MyLogger.getLogger();

    private static HttpConnection _httpInstance;

    private HttpConnection() {

    }

    /**
     * 获取一个新的DefaultHttpClient
     * 
     * @return
     */
    private DefaultHttpClient getClient() {
        // 设置我们的HttpClient支持HTTP和HTTPS两种模式
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, "UTF-8");
        HttpProtocolParams.setUseExpectContinue(params, true);
        /* 连接超时 */
        HttpConnectionParams.setConnectionTimeout(params, 30 * 1000);
        /* 请求超时 */
        HttpConnectionParams.setSoTimeout(params, 30 * 1000);
        HttpConnectionParams.setSocketBufferSize(params, 512);
        // 使用线程安全的连接管理来创建HttpClient
        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, schemeRegistry);
        DefaultHttpClient client = new DefaultHttpClient(ccm, params);
        // 异常恢复机制
        client.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(3, false));
        if (!Utils.isWifi()) {
            String proxyHost = android.net.Proxy.getDefaultHost();
            if (proxyHost != null) {// 如果是wap方式，要加网关
                HttpHost proxy = new HttpHost("10.0.0.172", 80);
                client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
            }
        }
        return client;
    }

    // private static DefaultHttpClient customerHttpClient;
    // /**
    // * 整个应用使用一个DefaultHttpClient
    // * @return
    // */
    // public static synchronized DefaultHttpClient getHttpClient() {
    // if (null == customerHttpClient) {
    // HttpParams params = new BasicHttpParams();
    // // 设置一些基本参数
    // HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    // HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
    // HttpProtocolParams.setUseExpectContinue(params, true);
    // // HttpProtocolParams
    // // .setUserAgent(
    // // params,
    // // "Mozilla/5.0(Linux;U;Android 2.2.1;en-us;Nexus One Build.FRG83) "
    // // +
    // //
    // "AppleWebKit/553.1(KHTML,like Gecko) Version/4.0 Mobile Safari/533.1");
    // // 超时设置
    // /* 从连接池中取连接的超时时间 */
    // ConnManagerParams.setTimeout(params, 1000);
    // /* 连接超时 */
    // HttpConnectionParams.setConnectionTimeout(params, 2000);
    // /* 请求超时 */
    // HttpConnectionParams.setSoTimeout(params, 4000);
    //
    // // 设置我们的HttpClient支持HTTP和HTTPS两种模式
    // SchemeRegistry schReg = new SchemeRegistry();
    // schReg.register(new Scheme("http", PlainSocketFactory
    // .getSocketFactory(), 80));
    // schReg.register(new Scheme("https", SSLSocketFactory
    // .getSocketFactory(), 443));
    //
    // // 使用线程安全的连接管理来创建HttpClient
    // ClientConnectionManager conMgr = new ThreadSafeClientConnManager(
    // params, schReg);
    // customerHttpClient = new DefaultHttpClient(conMgr, params);
    // customerHttpClient
    // .setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(
    // 3, false));
    // }
    // return customerHttpClient;
    // }

    public static HttpConnection getHttpConnection() {
        if (_httpInstance == null) {
            _httpInstance = new HttpConnection();
        }
        return _httpInstance;
    }

    public byte[] doHttpRequest(int method, String httpUri) throws HttpResponseException, ClientProtocolException, IOException {
        logger.e("--------url----------" + httpUri);
        if (0 == method) {
            return doGet(httpUri);
        }
        else {
            return doPost(httpUri);
        }
    }

    public byte[] doHttpPostRequest(String httpUri, String params) {
        byte data[] = null;
        try {
            URL url = new URL(httpUri);
            URLConnection connection = url.openConnection();
            connection.setDoOutput(true);
            OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
            out.write(params);
            out.flush();
            out.close();
            InputStream is = connection.getInputStream();
            ByteArrayOutputStream bos = new ByteArrayOutputStream();  
            byte[] buff = new byte[100];
            int rc = 0;
            while ((rc = is.read(buff, 0, 100)) > 0) {  
                bos.write(buff, 0, rc);  
            }
            data = bos.toByteArray();
            /*StringBuffer sb = new StringBuffer();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            data = (sb.toString()).getBytes();*/
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }
    
    
    
    /**
     * Json 格式参数 post 请求
     * @param httpUri
     * @param params
     * @return
     */
    public byte[] doHttpPostRequestByJson(String httpUri, String params) {
        byte data[] = null;
        try {
            URL url = new URL(httpUri);
            URLConnection connection = url.openConnection();
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setDoOutput(true);
            OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
            out.write(params);
            out.flush();
            out.close();
            InputStream is = connection.getInputStream();
            ByteArrayOutputStream bos = new ByteArrayOutputStream();  
            byte[] buff = new byte[100];
            int rc = 0;
            while ((rc = is.read(buff, 0, 100)) > 0) {  
                bos.write(buff, 0, rc);  
            }
            data = bos.toByteArray();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }
    

    public byte[] doHttpRequest(String httpUri, Map<String, String> postPair) throws HttpResponseException, ClientProtocolException, IOException {
        return doPost(httpUri, postPair);
    }

    private byte[] doPost(String url) throws ClientProtocolException, IOException, HttpResponseException {
        HttpPost _httpPost = null;
        _httpPost = new HttpPost(url);
        return getResponse(_httpPost);
    }

    private byte[] doPost(String url, Map<String, String> postPair) throws ClientProtocolException, IOException, HttpResponseException {
        HttpPost _httpPost = null;
        _httpPost = new HttpPost(url);
        if (postPair != null && postPair.size() > 0) {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            try {
                for (String s : postPair.keySet()) {
                    nameValuePairs.add(new BasicNameValuePair(s, postPair.get(s)));
                }
                _httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
            }
            catch (UnsupportedEncodingException e) {
                logger.e(e);
            }
        }
        return getResponse(_httpPost);
    }

    private byte[] doGet(String url) throws ClientProtocolException, IOException, HttpResponseException {
        HttpGet _httpGet = null;
        _httpGet = new HttpGet(url);
        return getResponse(_httpGet);
    }

    public HttpResponse doPost(long startPos, long packageSize, String url) throws ClientProtocolException, IOException, HttpResponseException {
        HttpPost _httpPost = null;
        _httpPost = new HttpPost(url);
        long endPos = startPos + packageSize;
        String range = "bytes=" + startPos + "-" + endPos;
        _httpPost.addHeader("Range", range);
        DefaultHttpClient client = getClient();
        HttpResponse response = client.execute(_httpPost);
        /* http status code */
        int code = response.getStatusLine().getStatusCode();
        logger.d("http response code : " + code);
        /* response data operation */
        if (code == HttpStatus.SC_OK || code == HttpStatus.SC_NOT_MODIFIED || code == HttpStatus.SC_PARTIAL_CONTENT) {
            return response;
        }
        else {
            return null;
        }
    }

    private boolean checkResponseEntity(HttpResponse response) {
        if (response == null)
            return false;
        if (response.getEntity().getContentLength() == 0 || (response.getEntity().getContentType() != null && response.getEntity().getContentType().getValue().contains("wml"))) {
            return false;
        }
        return true;
    }

    private byte[] getResponse(HttpUriRequest httpUriRequest) throws ClientProtocolException, IOException, HttpResponseException {
        DefaultHttpClient client = getClient();
        HttpResponse response = client.execute(httpUriRequest);
        /* http status code */
        int code = response.getStatusLine().getStatusCode();
        logger.d("http response code : " + code);
        byte[] responseData = null;
        /* response data operation */
        switch (code) {
        case HttpStatus.SC_OK:
            if (checkResponseEntity(response)) {
                responseData = EntityUtils.toByteArray(response.getEntity());
            }
            else {
                throw new HttpResponseException(101, "http connect error : connection is error or response data is wml");
            }
            break;
        case HttpStatus.SC_NOT_MODIFIED:
            // TODO HttpStatus.SC_NOT_MODIFIED:
            break;
        default:
            responseData = null;
        }
        if (client != null) {
            client.getConnectionManager().closeExpiredConnections();
            client = null;
        }
        if (responseData == null) {
            throw new HttpResponseException(code, "http connect error : " + code);
        }
        return responseData;
    }
}
